import { login } from "@/api/user";
import { UserContext } from "@/context/userContext";
import { Button, Form, Input } from "@ant-design/react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { router } from "expo-router";
import { useContext } from "react";
import { SafeAreaView } from "react-native-safe-area-context";

export default function SignInScreen() {
  const [form] = Form.useForm();
  const { setUser } = useContext(UserContext);

  const onFinish = (values: any) => {
    handleLogin(values);
  };

  const handleLogin = async (values: any) => {
    const res = await login(values);

    setUser(res.data.data.user);

    AsyncStorage.setItem("token", res.data.data.token);

    router.back();
  };

  return (
    <SafeAreaView>
      <Form form={form} onFinish={onFinish}>
        <Form.Item name="username">
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item name="password">
          <Input placeholder="请输入密码" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" onPress={() => form.submit()}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </SafeAreaView>
  );
}
